package org.web.ctrlcv.login.controller;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.web.filter.GenericFilterBean;

@Service(value="loginFilter")
public class LoginFilter extends GenericFilterBean {
	
	private static final int AJAX_HTTP_TIMEOUTME = 511;

	private static final String SESSION_EXPIRE_URI = "/loginForm.do?error=2";

	private static final String LOGIN_FORM_URI = "/loginForm.do";
	
	private static final String LOGOUT_URI = "/logout.do?error=2";

	//private List<String> urlList;
	
	private final String IKEP4LICENSE_USERCOUNT = "ikep4license.usercount";

	//protected FilterConfig filterConfig;
	
	//INIT 메소드가 실행되면 필터가 생성
	public void initFilterBean() throws ServletException {
		/*
		this.filterConfig = super.getFilterConfig();
		this.urlList = new ArrayList<String>();

		// properties에서 none_filter_urls 정보를 가져온다.
		Properties prop = PropertyLoader.loadProperties("/configuration/authentication.properties");
		String url = prop.getProperty("none_filter_urls").replaceAll(" ", "");
		String[] urls = url.split(",");

		this.urlList = Arrays.asList(urls);
		*/
	}
	
	public void destroy() {
		//this.filterConfig = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		/*
		try {
			HttpServletRequest req = (HttpServletRequest) request;

			HttpServletResponse res = (HttpServletResponse) response;

			HttpSession session = ((HttpServletRequest) request).getSession();

			String url = req.getServletPath();

			String redirectUri = LOGIN_FORM_URI;
			
			// 라이센스 세션 생성
			setLicenseSession();
			
			String ajaxFlag = req.getHeader("x-requested-with");
			Boolean timeOutFlag = false;
			
			// 제외 대상 Uri일 경우 체크
			if (urlList.contains(url)) {
				
				// ajax 호출이 아닐때만 세션 타임 체크
				if (!"XMLHttpRequest".equals(ajaxFlag)) {
					timeOutFlag = timeCheck(session, req);
				}
				
				if(!timeOutFlag) {
					chain.doFilter(request, response);
					return;
				} else {
					// 세션 시간 지났을 경우 로그아웃 페이지로 포워딩
					redirectUri = LOGOUT_URI;
				}
			} else {
				// session expire 처리 및 메인 화면 Ajax call skip 처리
				if (req.getRequestedSessionId() != null && !req.isRequestedSessionIdValid()) {
					
					// 헤더 interval일 경우, loginForm redirect 수행 안함
					if ("XMLHttpRequest".equals(ajaxFlag)) {
						res.sendError(AJAX_HTTP_TIMEOUTME, "sessiontimeout");
						return;
					}

					// session expire uri 대입
					redirectUri = SESSION_EXPIRE_URI;
				} else if (request instanceof HttpServletRequest) {
					// authentication check
					User user = (User) session.getAttribute("ikep.user");

					if (user != null) {
						// ajax 호출이 아닐때만 세션 타임 체크
						if (!"XMLHttpRequest".equals(ajaxFlag)) {
							timeOutFlag = timeCheck(session, req);
						}
						
						if(!timeOutFlag) {
							// 인증된 사용자면 next filter들을 수행한다.
							chain.doFilter(request, response);
							return;
						} else {
							// 세션 시간 지났을 경우 로그아웃 페이지로 포워딩
							redirectUri = LOGOUT_URI;
						}
					}  else {
						if ("XMLHttpRequest".equals(ajaxFlag)) {
							res.sendError(AJAX_HTTP_TIMEOUTME, "sessiontimeout");
							return;
						}
					}
				}
			}

			String preRedirectUri = getRequestUriWithParameter(req);
			session.setAttribute("ikep.preRedirectUri", preRedirectUri);
			ServletContext context = super.getServletContext();
			context.getRequestDispatcher(redirectUri).forward(request, response);
			// res.sendRedirect(req.getContextPath()+redirectUri);
		} catch (IOException ie) {
			throw new IKEP4ApplicationException("", ie);
		} catch (ServletException se) {
			throw new IKEP4ApplicationException("", se);
		}
		*/
	}
	
	private String getRequestUriWithParameter(HttpServletRequest request) {
		String queryString = request.getQueryString();
		String paramUri = request.getServletPath();
		
		/*
		if(paramUri.indexOf("portalMain.do") == -1 && paramUri.indexOf("/support/safety/updateSafetyMail.do") == -1) {
			paramUri = "/portal/main/portalMain.do?mainFrameUrl=" + paramUri;
		}
		*/
		
		if(paramUri.indexOf("/support/safety/updateSafetyMail.do") == -1) {
			paramUri = "/approval/work/apprlist/listApprTodo.do";
		}

		if (queryString != null) {
			paramUri += "?" + request.getQueryString();
		}

		return paramUri;
	}
	
	private boolean timeCheck(HttpSession session, HttpServletRequest request) {
		Boolean timeOutFlag = false;
		String paramUri = request.getServletPath();
		
		// 세션 타임 시간이 없거나 로그인, 로그아웃시에는 체크 안함
		if(session.getAttribute("ikep4.sesionTime") != null && paramUri.indexOf("/loginForm.do") == -1 && paramUri.indexOf("/login.do") == -1 && paramUri.indexOf("/logout.do") == -1){
			long loginTime = (Long)session.getAttribute("ikep4.sesionTime");
			long curTime = System.currentTimeMillis();
			
			long mills = curTime - loginTime;							
			long minute = mills / 60000;
			
			Properties portalProp = PropertyLoader.loadProperties("/configuration/portal-conf.properties");
			long checkMinute = Long.parseLong(portalProp.getProperty("portal.sesionTime"));
			
			if(minute > checkMinute){
				timeOutFlag = true;
			}						
		}
		
		
		if(!timeOutFlag) {
			// 세션 타임이 설정시간을 안지났을 경우 세션 시간 업데이트
			session.setAttribute("ikep4.sesionTime", System.currentTimeMillis());
		} else {
			// 세션 타임이 설정시간을 지났을 경우 세션 시간 삭제
			session.removeAttribute("ikep4.sesionTime");
		}
		
		return timeOutFlag;
	}
	
	public String serverURL(HttpServletRequest request){
		String protocol = request.getProtocol();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		String contextPath = request.getContextPath();
		
		StringBuffer url = new StringBuffer();
		
		if( protocol.toLowerCase().indexOf("https") >=0 ){
			url.append("https://");
		}else{
			url.append("http://");
		}
		
		url.append(serverName);
		
		if( serverPort != 80){
			url.append(":").append(serverPort);
		}
		
		url.append(contextPath);
		
		return url.toString();
	}

}
